﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MyPublisher.Configuration
{
    //host=155.35.248.109:80;userName=ca.com\zhach08;password=Woaixigua111
    public class ProxyString
    {
        public const string HOST_KEY = "host";
        public const string USERNAME_KEY = "username";
        public const string PASSWORD_KEY = "password";

        private Dictionary<string, string> KeyValues { get; set; }

        public ProxyString()
        {
            this.KeyValues = new Dictionary<string, string>()
            {
                {HOST_KEY,string.Empty},
                {USERNAME_KEY,string.Empty},
                {PASSWORD_KEY,string.Empty},
            };
        }

        public string Domain
        {
            get
            {
                string[] splits = UserName.Split(new char[] { '\\' });
                if (splits.Length > 1)
                {
                    return splits[0];
                }

                return string.Empty;
            }
        }

        public string Host
        {
            get { return KeyValues[HOST_KEY]; }
            set { KeyValues[HOST_KEY] = value; }
        }
        public string UserName
        {
            get
            {
                string[] splits = KeyValues[USERNAME_KEY].Split(new char[] { '\\' });
                if (splits.Length > 1)
                {
                    return splits[0];
                }
                return splits[0];
            }
            set { KeyValues[USERNAME_KEY] = value; }
        }
        public string Password
        {
            get { return KeyValues[PASSWORD_KEY]; }
            set { KeyValues[PASSWORD_KEY] = value; }
        }

        public override string ToString()
        {
            StringBuilder sb = new StringBuilder();
            foreach (KeyValuePair<string, string> keyValue in KeyValues)
            {
                sb.AppendFormat("{0}={1};", keyValue.Key, keyValue.Value);
            }
            return sb.ToString().TrimEnd(new char[] { ';' });
        }

        public static ProxyString Parse(string connString)
        {
            connString = connString.Trim(new char[] { ';' });
            ProxyString conn = new ProxyString();

            string[] splits = connString.Split(new char[] { ';' });
            foreach (string split in splits)
            {
                string[] keyvalue = split.Split(new char[] { '=' });
                conn.KeyValues[keyvalue[0]] = keyvalue[1];
            }

            return conn;
        }
    }
}
